﻿using System.Linq;

namespace QQ2564874169.Nubbo
{
    public abstract class NubboRequest
    {

        public string Uri { get; }

        protected NubboRequest(string uri)
        {
            Uri = uri;
        }

        protected internal abstract RequestParam ConvertToRequestParam();

        protected internal virtual string GetServiceName()
        {
            var items = Uri.Trim('/').Split('/');
            if (items.Length != 2)
            {
                throw new RequestException($"解析服务名失败：{Uri}。");
            }
            return items[1];
        }

        protected internal virtual NubboNode GetNode()
        {
            var items = Uri.Trim('/').Split('/');
            if (items.Length != 2)
            {
                throw new RequestException($"解析远程地址失败：{Uri}。");
            }
            var uri = items.First();
            items = uri.Split(':');
            if (items.Length == 1)
            {
                return new NubboNode
                {
                    Host = uri,
                    Port = 80
                };
            }
            if (items.Length == 2)
            {
                int port;
                if (int.TryParse(items[1], out port) == false)
                {
                    throw new RequestException($"{items[1]}无法解析为端口号。");
                }
                return new NubboNode
                {
                    Host = items[0],
                    Port = port
                };
            }
            throw new RequestException($"无法解析节点信息：{uri}");
        }
    }
}
